# -*- coding: utf-8 -*-
'''
Created on 2011-9-28

@author: deadblue
'''

from cn._2dland import cookie
from google.appengine.api import urlfetch
import urllib
import traceback

class NetworkException(Exception):
    ''' 网络异常 '''
    def __init__(self):
        pass

class HttpClient(object):

    def __init__(self):
        self.cookiejar = cookie.CookieJar()
        self.agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'

    def get(self, url, referer=None):
        ''' 执行GET操作 '''
        resp = None
        try :
            # 处理请求头
            headers = self._build_headers()
            if referer is not None:
                headers['Referer'] = referer

            # 发送GET请求
            resp = urlfetch.fetch(url=url,
                                  method=urlfetch.GET, 
                                  headers=headers,
                                  follow_redirects=False)
            if resp.headers.has_key('Set-Cookie'):
                self._store_cookie(resp.headers['Set-Cookie'])
        except :
            traceback.print_exc()
            raise NetworkException()
        return resp

    def post(self, url, data, referer=None):
        ''' 执行POST操作 '''
        resp = None
        try :
            headers = self._build_headers()
            headers['Content-Type'] = 'application/x-www-form-urlencoded'
            if referer is not None:
                headers['Referer'] = referer

            payload = data and urllib.urlencode(data) or None
            resp = urlfetch.fetch(url=url,
                                  method=urlfetch.POST,
                                  payload=payload,
                                  headers=headers,
                                  follow_redirects=False)
            if resp.headers.has_key('Set-Cookie'):
                self._store_cookie(resp.headers['Set-Cookie'])
        except :
            traceback.print_exc()
            raise NetworkException()
        return resp

    def _build_headers(self):
        ''' 构建请求头 '''
        headers = {'User-Agent': self.agent}
        if self.cookiejar.size() > 0:
            headers['Cookie'] = self.cookiejar.to_header_string()
        return headers

    def _store_cookie(self, raw):
        self.cookiejar.add_raw_cookies(raw)